import React, { Component, Fragment } from 'react';
import { Dispatch } from 'redux';
import { connect } from 'dva';

import moment from 'moment';
import router from 'umi/router';
import _ from 'lodash';

import { upload } from '@/utils/request';
import { Form } from '@ant-design/compatible';
import PageHeader from '@/components/PageHeader';
import { FormComponentProps } from '@ant-design/compatible/es/form';

import {
  Button,
  Card,
  Col,
  DatePicker,
  Input,
  InputNumber,
  Upload,
  Row,
  Select,
  Radio,
  message,
} from 'antd';
import { UploadOutlined } from '@ant-design/icons';
import '@ant-design/compatible/assets/index.css';

import { base_url } from '../../../../../config/request.config';
import JoinArea from './components/JoinArea';
import TableGarden from './components/TableGarden';

const { Search } = Input;
const { Option } = Select;
const { RangePicker } = DatePicker;
const { Item } = Form;

interface FranchiessProps extends FormComponentProps {
  dispatch: Dispatch<any>;
  match: { params: { fid: number } };
  location: { query: any };
  submitting: boolean;
  franchisee: any;
  INITINFO: any;
}

interface FranchiessState {
  canWithdrawDate: boolean;
  fileList: any;
  regionList: any;
  gardenList: any;
  parent_name: string;
}
@connect(({
  partnerFranchiseeEdit,
  common: { INITINFO },
  loading,
}: any) => ({
  franchisee: partnerFranchiseeEdit,
  INITINFO,
  submitting: loading.effects['partnerFranchiseeEdit/save'],
}))

class FranchiessAdd extends Component<FranchiessProps, FranchiessState> {
  timer: any = null;

  state: FranchiessState = {
    canWithdrawDate: true,
    fileList: [],
    regionList: [
      {
        is_exclusive: 0,
        parea_code: '00111',
        carea_code: '0011101',
        darea_code: '001110101',
      },
    ],
    gardenList: [],
    parent_name: '',
  };

  componentDidMount() {
    const { location: { query: { id } } } = this.props;
    if (id) this.fetchDetailInfo(id);

    const { dispatch } = this.props;
    dispatch({ type: 'common/fetchAddressList' });
    dispatch({
      type: 'partnerFranchiseeEdit/fetchFranchisees',
      payload: { name: '' },
    });
  }

  componentDidUpdate(prevProps: any) {
    const { location: { query: { id } } } = this.props;
    if (id && id !== prevProps.location.query.id) {
      this.fetchDetailInfo(id);
    }

    const { franchisee: { detail: franchisee, importGardenList } } = this.props;
    if (!_.isEqual(prevProps.franchisee.detail, franchisee)) {
      const values: any = _.pick(
        franchisee,
        'name',
        'address',
        'contact',
        'level',
        'phone',
        'day_max_quota',
        'is_postpone_withdraw',
        'consume_warn_amount',
      );

      values.day_max_quota /= 100;

      if (franchisee.parent) {
        const { parent: { id: key, name: label } } = franchisee;
        values.parent_id = { key, label };
      }

      if (franchisee.start_time && franchisee.end_time) {
        values.startEndTime = [moment(franchisee.start_time, 'YYYY-MM-DD'), moment(franchisee.end_time, 'YYYY-MM-DD')];
      }
      if (franchisee.can_withdraw_date) {
        values.can_withdraw_date = moment(franchisee.can_withdraw_date, 'YYYY-MM-DD');
      }

      const fileList = franchisee.file_link_list.length ? [{
        uid: 1,
        name: '附件',
        url: franchisee.file_link_list[0],
      }] : [];

      const { form: { setFieldsValue } } = this.props;
      // eslint-disable-next-line react/no-did-update-set-state
      this.setState({
        fileList,
        parent_name: franchisee.parent.name,
        canWithdrawDate: values.is_postpone_withdraw,
        regionList: franchisee.region_list || [],
        gardenList: franchisee.garden_list || [],
      }, () => setFieldsValue(values));
    }

    if (!_.isEqual(prevProps.franchisee.importGardenList, importGardenList)) {
      // eslint-disable-next-line react/no-did-update-set-state
      this.setState({ gardenList: importGardenList });
    }

    return null;
  }

  componentWillUnmount() {
    const { dispatch } = this.props;
    dispatch({ type: 'partnerFranchiseeEdit/clean' });
  }

  fetchDetailInfo = (id: number) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'partnerFranchiseeEdit/fetch',
      payload: { id },
    });
  }

  /**
   * 查询父级组织
   */
  handleSearchParent = (name: string) => {
    if (name) {
      clearTimeout(this.timer);

      this.timer = setTimeout(() => {
        const { dispatch } = this.props;
        dispatch({
          type: 'partnerFranchiseeEdit/fetchFranchisees',
          payload: { name },
        });
      }, 500);
    }
  };

  /**
   * 选择负责组织
   */
  handleChangeParent = (value: any) => {
    const { franchisee: { parentList = [] } } = this.props;
    console.log(value);
    const parent_name = parentList.find((parent: { id: number }) => parent.id === value.value).name;
    this.setState({ parent_name });

    const { form: { setFieldsValue } } = this.props;
    const level = parentList.find((item: any) => (item.id === value.value)).level + 1;
    setFieldsValue({ level });
  };

  /**
   * 上传图片
   */
  handleUpload = ({ file }: any) => {
    const name = file.name.length > 5 ? `${file.name.substring(0, 2)}...` : file.name;
    const fileList = [{
      uid: 1,
      name,
      url: file.url || '',
    }];

    this.setState({ fileList });
  };

  /**
   * 导入社区
   */
  handleImportGarden = () => {
    const { form: { getFieldValue } } = this.props;
    const phone = getFieldValue('phone');

    if (phone) {
      const { dispatch } = this.props;
      dispatch({
        type: 'partnerFranchiseeEdit/fetchGardensByPhone',
        payload: { phone },
      });
    }
  };

  // 基本信息
  renderBasicInfoElem = () => {
    const { fileList } = this.state;
    const {
      form: { getFieldDecorator },
      franchisee: { parentList = [] },
    } = this.props;

    const props: any = {
      accept: '.pdf',
      action: '',
      onChange: this.handleUpload,
      beforeUpload: this.beforeUpload.bind(this),
    };

    return (
      <Card
        title="基本信息"
        bordered={false}
        className="paddingB10"
      >
        <Row gutter={12}>
          <Col lg={8} md={12} sm={24}>
            <Item label="父级组织" colon={false}>
              {getFieldDecorator('parent_id', {
                rules: [{ required: true, message: '请输入父级组织' }],
              })(
                <Select
                  showSearch
                  placeholder="请选择父级组织"
                  labelInValue
                  defaultActiveFirstOption={false}
                  showArrow={false}
                  filterOption={false}
                  onSearch={this.handleSearchParent}
                  onChange={this.handleChangeParent}
                  notFoundContent={null}
                >
                  {parentList.map((item: any) => (
                    (item.status === 1
                      && <Option key={item.id} value={item.id}>{item.name}</Option>
                    )
                  ))}
                </Select>,
              )}
            </Item>
          </Col>
          <Col lg={8} md={12} sm={24}>
            <Item label="加盟级别" colon={false}>
              {getFieldDecorator('level')(
                <Input placeholder="选定父级组织自动识别" disabled />,
              )}
            </Item>
          </Col>
          <Col lg={8} md={12} sm={24}>
            <Item label="加盟周期" colon={false}>
              {getFieldDecorator('startEndTime', {
                rules: [{ required: true, message: '请选择加盟日期' }],
              })(
                <RangePicker
                  // disabled={[!!franchisee?.detail?.start_time, false]}
                  disabled={[false, false]}
                />,
              )}
            </Item>
          </Col>
        </Row>
        <Row gutter={12}>
          <Col lg={8} md={12} sm={24}>
            <Item label="商户名称" colon={false}>
              {getFieldDecorator('name', {
                rules: [{ required: true, message: '请输入商户名称' }],
              })(
                <Input placeholder="请输入商户名称" />,
              )}
            </Item>
          </Col>
          <Col lg={8} md={12} sm={24}>
            <Item label="商户地址" colon={false}>
              {getFieldDecorator('address', {
                rules: [{ required: true, message: '请输入商户地址' }],
              })(
                <Input placeholder="请输入商户地址" />,
              )}
            </Item>
          </Col>
          <Col lg={8} md={12} sm={24}>
            <Item label="营业执照或身份证" colon={false}>
              {getFieldDecorator('file_link_list', {
                initialValue: fileList,
                rules: [{ required: true, message: '请上传营业执照或身份证' }],
              })(
                <Upload {...props} fileList={fileList}>
                  <Button
                    type="primary"
                    style={{ fontSize: 12 }}
                    size="small"
                    ghost
                  >
                    <UploadOutlined />
                    上传文件
                  </Button>
                </Upload>,
              )}
            </Item>
          </Col>
        </Row>
        <Row gutter={12}>
          <Col lg={8} md={12} sm={24}>
            <Item label="　联系人" colon={false}>
              {getFieldDecorator('contact', {
                rules: [{ required: true, message: '请输入联系人' }],
              })(
                <Input placeholder="请输入联系人" />,
              )}
            </Item>
          </Col>
          <Col lg={8} md={12} sm={24}>
            <Item label="手机号码" colon={false}>
              {getFieldDecorator('phone', {
                rules: [{ required: true, message: '请输入手机号码' }],
              })(
                <Search
                  placeholder="请输入"
                  type="number"
                  enterButton="导入社区"
                  onSearch={this.handleImportGarden}
                />,
              )}
            </Item>
          </Col>
        </Row>
      </Card>
    );
  };

  /**
   * 选择提现设置
   */
  handleWithdraw = (e: any) => this.setState({ canWithdrawDate: !!e.target.value });

  // 账户设置
  renderAccountSettingElem = () => {
    const { canWithdrawDate } = this.state;
    const { form: { getFieldDecorator } } = this.props;

    return (
      <Card
        title="账户设置"
        bordered={false}
        className="paddingB10"
      >
        <Form layout="vertical" hideRequiredMark>
          <Row gutter={{ md: 8, xl: 48, lg: 48 }}>
            <Col md={10} sm={24}>
              <div className="dottedBox">
                <div className="subtitle marginB12">提现账户</div>
                <Item
                  label="　　延期提现设置"
                  colon={false}
                  className="marginB0Import"
                >
                  {getFieldDecorator('is_postpone_withdraw', {
                    rules: [{ required: true, message: '请选择提现设置' }],
                  })(
                    <Radio.Group onChange={this.handleWithdraw}>
                      <Radio value={0}>关闭</Radio>
                      <Radio value={1}>开启</Radio>
                    </Radio.Group>,
                  )}
                </Item>
                <Item
                  colon={false}
                  label="　　延期提现日期"
                  className="marginB0Import"
                >
                  {
                    !!canWithdrawDate && getFieldDecorator('can_withdraw_date', {
                      rules: [{ required: true, message: '请选择提现日期' }],
                    })(
                      <DatePicker
                        placeholder="请选择"
                        style={{ width: '70%' }}
                      />,
                    )
                  }
                  {!canWithdrawDate && (
                    <DatePicker style={{ width: '70%' }} disabled />
                  )}
                </Item>
                <Item
                  label="单日提现上限金额"
                  colon={false}
                  className="marginB0Import"
                >
                  {getFieldDecorator('day_max_quota', {
                    rules: [{ required: true, message: '请输入上限余额' }],
                  })(
                    <InputNumber
                      min={0}
                      placeholder="请输入提现上限金额"
                      style={{ width: '70%' }}
                    />,
                  )}
                </Item>
              </div>
            </Col>
            <Col md={10} sm={24}>
              <div className="dottedBox">
                <div className="subtitle marginB12">充值账户</div>
                <Item
                  label="设置报警余额"
                  colon={false}
                  className="marginB0Import"
                >
                  {getFieldDecorator('consume_warn_amount', {
                    rules: [{ required: true, message: '请设置报警报警' }],
                  })(
                    <InputNumber
                      style={{ width: '70%' }}
                      placeholder="请输入报警余额"
                    />,
                  )}
                </Item>
              </div>
            </Col>
          </Row>
        </Form>
      </Card>
    );
  };

  // 加盟区域
  renderJoinAreaElem = () => {
    const { regionList } = this.state;
    const {
      form: { getFieldDecorator },
      INITINFO: { addressList },
    } = this.props;

    return (
      <>
        {regionList.length ? (
          <Card
            title="加盟区域"
            className="paddingT10"
            bordered={false}
          >
            {getFieldDecorator('regionList', {
              initialValue: regionList,
              rules: [{ required: true, message: '请填写加盟区域' }],
            })(
              <JoinArea addressList={addressList} />,
            )}
          </Card>
        ) : null}
      </>
    );
  };

  // 社区列表
  renderCommunityListElem = () => {
    const { gardenList } = this.state;
    const { form: { getFieldDecorator } } = this.props;

    return (
      <Card
        title="社区列表"
        className="paddingT10"
        bordered={false}
      >
        {getFieldDecorator('gardeList', {
          initialValue: gardenList,
        })(<TableGarden />)}
      </Card>
    );
  };

  /**
   * 保存
   */
  validate = () => {
    const { form: { validateFieldsAndScroll } } = this.props;
    validateFieldsAndScroll((error, values) => {
      if (error) return;

      const { garden_id_list } = values;
      values = {
        ...values,
        garden_id_list: garden_id_list || '[]',
      };

      const {
        startEndTime,
        gardeList = [],
        regionList = [],
        ...params
      } = values;

      const { parent_name } = this.state;
      params.parent_name = parent_name;
      params.day_max_quota *= 100;

      if (startEndTime) {
        params.start_time = moment(startEndTime[0]).format('YYYY-MM-DD');
        params.end_time = moment(startEndTime[1]).format('YYYY-MM-DD');
      }

      if (gardeList && gardeList.length) {
        params.garden_id_list = JSON.stringify(
          gardeList
            .filter((garden: { selected: boolean }) => garden.selected)
            .map((garden: { id: number }) => garden.id),
        );
      }

      if (regionList) {
        params.region_list = JSON.stringify(regionList);
      }

      const { fileList } = this.state;
      params.file_link_list = fileList.length
        ? JSON.stringify(fileList.map((file: { url: string }) => file.url)) : [];


      const { location: { query: { id } } } = this.props;
      if (id) params.id = id;

      const parent_id = params.parent_id ? params.parent_id.key : 0;
      const can_withdraw_date = params.can_withdraw_date ? moment(params.can_withdraw_date).format('YYYY-MM-DD') : '';
      const new_params = { ...params, parent_id, can_withdraw_date };

      const { dispatch } = this.props;
      dispatch({
        type: 'partnerFranchiseeEdit/save',
        payload: new_params,
      });
    });
  };

  /**
   * 上传之前
   */
  beforeUpload(file: any) {
    const formData = new FormData();
    formData.append('file', file);

    upload(
      `${base_url}/franchise/franchisee/upload_file`,
      { body: formData },
    ).then(({ code, body }) => {
      if (code === 0) {
        message.success('上传成功');
        const { fileList } = this.state;
        fileList[fileList.length - 1].url = body;
        this.setState({ fileList });
      }
    });
  }

  render() {
    const { submitting } = this.props;

    return (
      <Fragment>
        <PageHeader />

        <Form
          hideRequiredMark
          className="tableListForm"
        >
          {this.renderBasicInfoElem()}
          {this.renderAccountSettingElem()}
          {this.renderJoinAreaElem()}
          {this.renderCommunityListElem()}
        </Form>

        <Card bordered={false}>
          <Button
            type="primary"
            onClick={this.validate}
            loading={submitting}
          >
            提交
          </Button>
          <Button
            type="primary"
            ghost
            style={{ marginLeft: 16 }}
            onClick={() => router.goBack()}
          >
            取消
          </Button>
        </Card>
      </Fragment>
    );
  }
}

export default Form.create<FranchiessProps>()(FranchiessAdd);
